﻿using FileSystem.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FileSystem.impl.Actions
{
    class Find : ActionABC, INodeVisitor, IAction
    {
        private string nodeName;
        private bool executeSucceeded = false;
        private IResult lastResult;
        private IFSDirectory directory;
        private StringBuilder sb = new StringBuilder();

       
        public Find(string nodeName)
            : base(new HelpDescription() { Name = "find", Description = "find files in current directory." })
        {
            this.nodeName = nodeName;
		}

        //public Find()
        //    : base(new HelpDescription() { Name = "find", Description = "find files in current directory." })
        //{

        //}
     
        #region IAction Members

        public override IResult execute()
        {
            this.directory = AppResources.getInstance().getFileSystem().CurrentDirectory;
            this.directory.Accept(this);
            
            if(sb.Length == 0)
            {
                return new Result(true, "No match found");
            }
                
            return new Result(sb.ToString());
        }

        #endregion

        
        #region INodeVisitor Members

        public void VisitFile(IFSFile file)
        {
            lastResult = new Result(true, "Given name is not a directory");
            executeSucceeded = true;
        }

        public void VisitDirectory(IFSDirectory directory)
        {
            for (int iNode = 0; iNode < directory.numNodes(); iNode++)
            {
                IFSNode node = directory.getNode(iNode);
                if (node.getName() == nodeName)
                {
                    sb.AppendLine(node.getFQName());
                }
                node.Accept(this);

            }

            executeSucceeded = true;
        }

        public void VisitLink(IFSLink link)
        {
            if (link.GetLinkedNode() != null)
                link.GetLinkedNode().Accept(this);
        }

        #endregion

    }
}
